package com.it.windows;

import com.it.operator.utils.SourceUtils;
import com.it.pojo.Event;
import com.it.pojo.UrlVisitBean;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.AggregateFunction;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;

/**
 * @author code1997
 */
public class WindowAggAndProcessTest {

    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment executionEnvironment = StreamExecutionEnvironment.getExecutionEnvironment();
        SingleOutputStreamOperator<Event> eventSource = SourceUtils.getEventSource(executionEnvironment)
                //调用flink内置的针对于有序流的watermark策略
                .assignTimestampsAndWatermarks(WatermarkStrategy.<Event>forBoundedOutOfOrderness(Duration.ofSeconds(2)).withTimestampAssigner(new SerializableTimestampAssigner<Event>() {
                    @Override
                    public long extractTimestamp(Event element, long recordTimestamp) {
                        return element.timestamp;
                    }
                }));
        eventSource.keyBy(event -> event.url)
                //滑动事件时间窗口
                //.window(SlidingEventTimeWindows.of(Time.hours(1)))
                //滚动事件时间窗口：默认是整点，可以通过offset来进行调整
                .window(TumblingEventTimeWindows.of(Time.seconds(2L)))
                //聚合函数:
                .aggregate(new WindowAggAndProcessTest.MyAggFunction(),
                        new WindowAggAndProcessTest.MyProcessFunction()
                ).print();
        executionEnvironment.execute();
    }

    public static class MyAggFunction implements AggregateFunction<Event, Long, Long> {

        @Override
        public Long createAccumulator() {
            return 0L;
        }

        @Override
        public Long add(Event value, Long accumulator) {
            return accumulator + 1;
        }

        @Override
        public Long getResult(Long accumulator) {
            return accumulator;
        }

        @Override
        public Long merge(Long a, Long b) {
            return null;
        }
    }

    public static class MyProcessFunction extends ProcessWindowFunction<Long, UrlVisitBean, String, TimeWindow> {

        @Override
        public void process(String s, ProcessWindowFunction<Long, UrlVisitBean, String, TimeWindow>.Context context, Iterable<Long> elements, Collector<UrlVisitBean> out) throws Exception {
            long start = context.window().getStart();
            long end = context.window().getEnd();
            long count = elements.iterator().next();
            out.collect(new UrlVisitBean(s, count, start, end));
        }
    }
}
